﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Disco.Ontology;

namespace Disco.Web.Api
{
    public class BasicAuthenticationAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            string userName = "anonymous";
            string password = null;
            if (null != actionContext.Request.Headers.Authorization)
            {
                string authToken = actionContext.Request.Headers.Authorization.Parameter;
                string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));

                userName = decodedToken.Substring(0, decodedToken.IndexOf(':'));
                password = decodedToken.Substring(decodedToken.IndexOf(':') + 1);
            }

            User user = null;
            using (var context = new OntologyContext())
            {
                user = context.Users.SingleOrDefault(u => u.Alias == userName);
            }
            HttpContext.Current.User = new GenericPrincipal(new UserIdentity(user, userName), new string[] { });
            Thread.CurrentPrincipal = HttpContext.Current.User;

            base.OnActionExecuting(actionContext);
        }
    }
}